<?php

namespace app\utils\base\database;

class Migrate
{
    /**
     * 导出-安装-数据表
     * @param string $paramObj
     * @return array
     */
    public function exportInstallTable($paramObj=""){
        $dataObj=paramsObj();
        $dataObj->request=paramsObj();
        $dataObj->data=paramsObj();
        $dataObj->result=array();

        $final_arr=logInit();
        if($final_arr["error_no"]==0){
            $mixed=parseToArr($paramObj,"mixed",0);
            $params=parseToArr($paramObj,"params",array());
            $messages=parseToArr($paramObj,"messages",array());
            $rules=array(
                'database' => 'require',
                'version' => 'require',
                'outFile' => '',
                'filename' => '',
                'type' => '',
                'link' => '',
            );
            $dataDefault=array();
            $dataDefault["type"]="1"; // 默认 表存在删除，在创建，1 检测是否存在，存在则不创建 2 不检测直接创建
            $paramsObj=paramsObj();
            $paramsObj->params=$params;
            $paramsObj->mixed=$mixed;
            $paramsObj->rules=$rules;
            $paramsObj->messages=$messages;
            $paramsObj->dataDefault=$dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if($checkResult["error_no"]==0){
                $dataObj->request=$checkResult["result"];
            }else{
                $final_arr=logCallErrorMsg($final_arr,$checkResult);
            }
        }
        if($final_arr["error_no"]==0){
            $migrateData=$this->getMigrateData($dataObj->request->database,$dataObj->request->version);
            $delimiter="\r\n";
            $table_pre=config("database.default.tb_pre","");
            $sql="";
            $sql.=$delimiter;
            $sql.="SET NAMES utf8mb4;".$delimiter;
            $sql.="SET FOREIGN_KEY_CHECKS = 0;".$delimiter.$delimiter;
            foreach($migrateData["tableList"] as $lval){
                $createSql="show create table {$table_pre}{$lval['name']}";
                if($dataObj->request->link=="api"){
                    $result=Db()->changeConnect("api")->fetch(Db()->changeConnect("api")->select($createSql));
                }else{
                    $result=Db()->fetch(Db()->select($createSql));
                }
                if($result){
                    $rowData=$result[0];
                    $table_ddl=$rowData["Create Table"];
                    $table_ddl=preg_replace("/AUTO_INCREMENT=(\d+)\s/","",$table_ddl);
                    if($lval['name']=="module"){
                        $table_ddl.=" AUTO_INCREMENT=10";
                    }

                    $sql .= "-- ----------------------------".$delimiter;
                    $sql .= "-- Table structure for `".$lval['name']."`".$delimiter;
                    $sql .= "-- ----------------------------".$delimiter;

                    if($dataObj->request->type=="1"){
                        $sql.=str_replace("CREATE TABLE `{$table_pre}{$lval['name']}` ","CREATE TABLE IF NOT EXISTS `{table_pre}{$lval['name']}` ",$table_ddl).";".$delimiter.$delimiter;
                    }else if($dataObj->request->type=="2"){
                        $sql.=str_replace("CREATE TABLE `{$table_pre}{$lval['name']}` ","CREATE TABLE `{table_pre}{$lval['name']}` ",$table_ddl).";".$delimiter.$delimiter;
                    }else{
                        $sql .= "DROP TABLE IF EXISTS `{table_pre}".$lval['name']."`;".$delimiter;
                        $sql.=str_replace("CREATE TABLE `{$table_pre}{$lval['name']}` ","CREATE TABLE `{table_pre}{$lval['name']}` ",$table_ddl).";".$delimiter.$delimiter;
                    }

                    //查询数据
                    $record=isset($lval["record"])?$lval["record"]:0;
                    if($record){
                        $replace=isset($lval["replace"])?$lval["replace"]:"";
                        $removeField=isset($lval["removeField"])?$lval["removeField"]:"";
                        $condition=isset($lval["condition"])?$lval["condition"]:"";
                        $condition=$condition?" where ".$condition:"";
                        //查询当前表数据
                        $selectSql="select * from {$table_pre}{$lval['name']}{$condition}";
                        if($dataObj->request->link=="api"){
                            $tableData=Db()->changeConnect("api")->select($selectSql);
                        }else{
                            $tableData=Db()->select($selectSql);
                        }
                        if($tableData){
                            $fields=$tableData[0];
                            if($removeField && is_array($removeField)){
                                foreach($removeField as $fd){
                                    unset($fields[$fd]);
                                }
                            }
                            $fields="`".implode("`,`",array_keys($fields))."`";
                            $sql .= "-- ----------------------------".$delimiter;
                            $sql .= "-- Records for `".$lval['name']."`".$delimiter;
                            $sql .= "-- ----------------------------".$delimiter;
                            foreach($tableData as $dkey=>$dval){
                                $sql .= "INSERT INTO `{table_pre}".$lval['name']."`({$fields}) VALUES (";
                                foreach($dval as $ddkey=>$ddval){
                                    if($removeField && in_array($ddkey,$removeField)){
                                        continue;
                                    }
                                    if(isset($replace[$ddkey][$ddval])){
                                        $ddval=$replace[$ddkey][$ddval];
                                    }
                                    if(is_numeric($ddval)){
                                        $sql .= $ddval.", ";
                                    }else{
                                        $sql .= "'".addslashes($ddval)."', ";
                                    }
                                }
                                $sql=rtrim($sql,", ");
                                $sql .=");".$delimiter;
                            }
                            $sql .=$delimiter;
                        }
                    }
                }
            }
            $sql.="SET FOREIGN_KEY_CHECKS = 1;".$delimiter.$delimiter;
            $dataObj->data->sql=$sql;
            unset($sql);
        }
        if($final_arr["error_no"]==0){
            if($dataObj->request->outFile){
                $filename=$dataObj->request->filename?$dataObj->request->filename:"table.sql";
                $outFile=runtimePath("migrate/install_table/".str_replace(".","_",$dataObj->request->version));
                $outFile=str_replace("\\","/",$outFile);
                $this->mkdir($outFile);
                $filePath=$outFile.$filename;
                file_put_contents($filePath,$dataObj->data->sql);
            }else{
                $return=array();
                $return["sql"]=$dataObj->data->sql;
                $final_arr["result"]=$return;
            }
        }
        return $final_arr;
    }

    /**
     * 获取迁移数据
     * @param $database
     * @param $version
     * @return array
     */
    public function getMigrateData($database,$version){
        if($database=="cms"){
            if($version=="init"){
                return $this->generateMigrateData_cms_init0();
            }else if($version=="member"){
                return $this->generateMigrateData_cms_member();
            }else if($version=="shop"){
                return $this->generateMigrateData_cms_shop();
            }else if($version=="domain_auth"){
                return $this->generateMigrateData_cms_domain_auth();
            }else if($version=="menu_data"){
                return $this->generateMigrateData_cms_menu_data();
            }else if($version=="api_doc"){
                return $this->generateMigrateData_cms_api_doc();
            }else if($version=="page_flip_optimize"){
                return $this->generateMigrateData_cms_page_flip_optimize();
            }else if($version=="receive_data"){
                return $this->generateMigrateData_cms_receive_data();
            }else if($version=="category"){
                return $this->generateMigrateData_cms_ltcms_category();
            }else if($version=="qr_code"){
                return $this->generateMigrateData_cms_qr_code();
            }else if($version=="short_code"){
                return $this->generateMigrateData_cms_short_code();
            }else if($version=="auth_identity"){
                return $this->generateMigrateData_cms_auth_identity();
            }else if($version=="op_check"){
                return $this->generateMigrateData_cms_op_check();
            }else if($version=="platform_response"){
                return $this->generateMigrateData_cms_platform_response();
            }
        }
        return array();
    }

    /**
     * 平台响应
     */
    public function generateMigrateData_cms_platform_response(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"platform_app",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"platform_menu",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"platform_reply",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"platform_certificate",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"platform_merchant",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"platform_token",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 操作记录
     */
    public function generateMigrateData_cms_op_check(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"op_check",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 用户身份
     */
    public function generateMigrateData_cms_auth_identity(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"auth_identity",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity_limit",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity_setting",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_auth_identity",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 短连接
     */
    public function generateMigrateData_cms_short_code(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"short_code",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 二维码
     */
    public function generateMigrateData_cms_qr_code(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"qrcode",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 分类
     */
    public function generateMigrateData_cms_ltcms_category(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"category_gf",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 1.0.0 数据
     */
    public function generateMigrateData_cms_init0(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"ad_manage",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"ad_position",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"module",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"map_relation",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"cache",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"friend_link",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"member_admin",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"friend_link_group",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"single_page_group",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"member_admin_func",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"member_admin_menu",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"member_admin_role",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"member_admin_role_func",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"sessions",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"setting",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"single_page",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"category",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"commend_module_data",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"category_child",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"category_data",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"category_op",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"software_upgrade_log",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"fields",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"log_operation",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 1.0.1 会员登录数据
     */
    public function generateMigrateData_cms_member(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"oauth",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"oauth_show",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"oauth_users",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_auth",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_token",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"app",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"login_st",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"login_tgt",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"ucenter_service",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"ucenter_service_data",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_app",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_platform",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"verify_code",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"verify_code_service",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"wechat_menu",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"wechat_auto_reply",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_group",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 1.0.1 会员登录数据
     */
    public function generateMigrateData_cms_shop(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"goods",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"model",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_attribute",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_car",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_photo",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_photo_relation",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"group_price",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"plugin",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"plugin_record",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"plugin_status",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"plugin_status_user",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"plugin_upgrade_log",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"prop",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"prop_data",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"op_check",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"products",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"promotion",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"refundment",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"spec",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"spec_photo",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"address",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"areas",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"brand",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"brand_category",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"commend_goods",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"comment",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"delivery",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"delivery_doc",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"delivery_extend",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"discussion",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_category",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_category_extend",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"goods_reserve_store_nums",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"model_attribute",
            "record"=>"0",
        );

        $tableList[]=array(
            "name"=>"order",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"order_goods",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"order_log",
            "record"=>"0",
        );

        $tableList[]=array(
            "name"=>"payment",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"payment_show",
            "record"=>"0",
        );

        $tableList[]=array(
            "name"=>"safe_verify",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"sellers",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"sellers_auth",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"send_address",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_habits",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"wechat_certificate",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"users_auth_identity",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity_limit",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity_limit_record",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"auth_identity_setting",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 1.0.1 域名授权
     */
    public function generateMigrateData_cms_domain_auth(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"domain_auth",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"domain_auth_status",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"domain_auth_status_user",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"cms_project",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"cms_project_setting",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 菜单生成
     */
    public function generateMigrateData_cms_menu_data(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"menu_data",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 菜单生成
     */
    public function generateMigrateData_cms_api_doc(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"api_doc",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 菜单优化生成
     */
    public function generateMigrateData_cms_page_flip_optimize(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"page_flip_optimize",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"page_flip_optimize_lock",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 收集数据
     */
    public function generateMigrateData_cms_receive_data(){
        $tableList=array();
        $tableList[]=array(
            "name"=>"install_domain",
            "record"=>"0",
        );
        $tableList[]=array(
            "name"=>"install_log",
            "record"=>"0",
        );
        $result=array();
        $result["tableList"]=$tableList;
        return $result;
    }

    /**
     * 获取随机字符串
     * @param int $length
     * @return string
     */
    public function generateRandomString($minLen = 5, $maxLen = 10)
    {
        $characters = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        foreach (range(1, rand($minLen, $maxLen)) as $i) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    /**
     * 创建目录
     * @param $dir
     */
    public function mkdir($dir){
        if(!is_dir($dir)){
            @umask(000);
            return @mkdir($dir,0777,true);
        }
        return true;
    }
}